<template>
  <div class="app-container">
    <el-row :gutter="24">
      <el-col :span="24" :xs="24">
        <el-card>
          <div class="filter-container">

            <el-button class="filter-item" icon="el-icon-plus" style="margin-left:20px" type="primary"
                       @click="createTask">
              定时出账
            </el-button>
          </div>
          <div class="app-container">
            <el-table
              :key="tableKey"
              ref="bill-task"
              v-loading="listLoading"
              :cell-style="{padding:0+'px'}"
              :data="list"
              :row-style="{height:40+'px'}"
              border
              fit
              height="700"
              highlight-current-row
              stripe
              style="width: 100%;"
            >
              <el-table-column align="center" label="名称" width="80">
                <template v-slot="{row}">
                  <span>{{ row.name }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="类型">
                <template v-slot="{row}">
                  {{ row.cron_type | cronTypeFilter }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="任务状态">
                <template v-slot="{row}">
                  <el-button v-if="row.status === 0" type="danger" size="mini" circle icon="el-icon-video-pause" @click="handleActive(row)" />
                  <el-button v-if="row.status === 1" type="success" size="mini" circle icon="el-icon-video-play" @click="handleDisable(row)" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="执行状态">
                <template v-slot="{row}">
                  {{ row.run_status | runStatusFilter }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="上次执行时间" width="180">
                <template v-slot="{row}">
                  <span>{{ row.run_time | formatTime }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="下次执行时间" width="180">
                <template v-slot="{row}">
                  <span>{{ row.next_time  }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="创建时间" width="180">
                <template v-slot="{row}">
                  <span>{{ row.create_time | formatTime }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" class-name="small-padding fixed-width" label="操作"
                               width="120">
                <template v-slot="{row,$index}">
                  <el-button v-if="checkPermission('编辑任务')" size="mini" type="primary" @click="updateTask(row)">
                    修改
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total>0" :limit.sync="listQuery.pageSize" :page.sync="listQuery.page" :total="total"
                        @pagination="getTaskList"/>
            <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible"
                       custom-class="window-small-width" width="40%">
              <el-form ref="dataForm" :model="form.model" :rules="form.rules" label-position="right" label-width="80px"
              >
                <el-form-item label="名称" prop="name">
                  <el-input v-model="form.model.name" style="width:220px "/>
                </el-form-item>
                <el-form-item label="定时周期" prop="cron_spec">
                  <el-select v-model="form.model.cron_type" placeholder="月" style="margin-top: 1px;width: 80px">
                    <el-option
                      v-for="item in [{'name':'每天',value:2},{'name':'每月',value:4}]"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value">
                    </el-option>
                  </el-select>
                  <span style="margin-left: 5px;margin-right: 5px" v-if="form.model.cron_type === 4">的</span>
                  <el-select v-if="form.model.cron_type ===4" v-model="form.model.day" placeholder="日"
                             style="margin-top: 5px;width: 80px">
                    <el-option
                      v-for="item in 31"
                      :key="item"
                      :label="item+' 日'"
                      :value="item">
                    </el-option>
                  </el-select>
                  的
                  <el-select  v-model="form.model.hour" placeholder="请选择" style="margin-top: 5px;width: 80px">
                    <el-option
                      v-for="item in 24"
                      :key="item"
                      :label="item-1+' 时'"
                      :value="item-1">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                  取消
                </el-button>
                <el-button :loading="submitLoading" type="primary"
                           @click="dialogStatus === 'create' ? handleCreate():handleUpdate()">
                  确认
                </el-button>
              </div>
            </el-dialog>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination';
import {checkPermission} from "@/utils/permission";
import {fetchBillTaskList,createBillTask,updateBillTask} from "@/api/finance";
import {activeTask,disableTask,deleteTask} from "@/api/task";
import moment from "moment";

const TaskTypeBill = 2

const defaultTask = {
  name: '',
  cron_spec: '',
  cron_type: 2,
  type:TaskTypeBill,
  month: 1,
  week: 0,
  day: 1,
  hour: 0,
  minute: 0
}

export default {
  name: 'BillCron',
  components: { Pagination},
  data() {
    return {
      tableKey: 0,
      dialogFormVisible: false,
      deviceLogs: [],
      listLoading: true,
      submitLoading: false,
      list: [],
      dialogStatus: 'create',
      textMap: {
        update: '编辑定时出账',
        create: '创建定时出账'
      },
      total: 0,
      listQuery: {
        page: 1,
        pageSize: 20
      },
      form: {
        model:{},
        rules:{}
      },
    }
  },
  filters:{
    statusFilter(status) {
      const statusMap = {
        0: '未激活',
        1: '已激活'
      }
      return statusMap[status]
    },
    formatTime(dateStr) {
      let t = moment(dateStr);
      if(t.millisecond() === 0) {
        return '-'
      }
      return t.format('YYYY-MM-DD HH:mm:ss')
    },
    runStatusFilter(status) {
      const statusMap = {
        0: '正常',
        1: '错误'
      }
      return statusMap[status]
    },
    cronTypeFilter(t){
      const statusMap = {
        2: '每日',
        4: '每月'
      }
      return statusMap[t] || '-'
    }
  },
  created() {
    this.temp = defaultTask
    this.getTaskList()
  },
  methods: {
    checkPermission,
    getTaskList() {
      this.listLoading = true
      let queryData = Object.assign({}, this.listQuery)
      fetchBillTaskList(queryData).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    genCronSpec() {
      let tmp = ["*", "*", "*", "*", "*"]  //Seconds Minutes Hours DayOfMonth Month DayOfWeek
      switch (this.form.model.cron_type) {
        case 2://每天
          tmp[0] = this.form.model.minute
          tmp[1] = this.form.model.hour
          break
        case 4: //每月
          tmp[2] = this.form.model.day
          tmp[3] = this.form.model.month
          break
      }
      return tmp.join(" ")
    },
    createTask() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleCreate() {
      this.submitLoading = true
      this.form.model.cron_spec = this.genCronSpec()
      createBillTask(this.form.model).then(resp => {
        if (resp.code === 20000) {
          this.getTaskList()
          this.$message.success("操作成功")
        } else {
          this.$message.error(resp.message)
        }
        setTimeout(() => {
          this.submitLoading = false
        }, 1.5 * 1000)
      })
    },
    updateTask(row) {
      if (row.status === 1) {
        this.$message.error("请先停用该任务")
        return
      }
      this.resetTemp()
      this.form.model = Object.assign({},row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    handleUpdate() {
      this.submitLoading = true
      this.form.model.cron_spec = this.genCronSpec()
      let data = Object.assign({}, this.form.model)
      updateBillTask(data).then(resp => {
        if (resp.code === 20000) {
          this.$message.success("修改成功")
        } else {
          this.$message.error(resp.message)
        }
        setTimeout(() => {
          this.submitLoading = false
          this.dialogFormVisible = false
          this.getTaskList()
        }, 1.5 * 1000)
      })
    },
    handleDelete(row) {
      if (row.status === 1) {
        this.$message.error("请先停用该任务")
        return
      }
      this.$confirm('此操作将永久删除该计划任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTask({task_id: row.id}).then(response => {
          if (response.code === 20000) {
              this.$message.success("成功删除")
            this.getTaskList()
          } else {
            this.$message.error(response.message)
          }
        })
      })
    },
    handleDisable(row) {
      this.$confirm('立即暂停' + row.name + '计划任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        disableTask({task_id: row.id}).then(response => {
          if (response.code == 20000) {
            row.status = 0
            this.$message.success("已暂停")
            this.getTaskList()
          } else {
            this.$message.error(response.message)
          }
        })
      })
    },
    handleActive(row) {
      this.$confirm('立即激活' + row.name + '任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        activeTask({task_id: row.id}).then(response => {
          if (response.code == 20000) {
            row.status = 1
            this.$message.success("已激活")
            this.getTaskList()
          } else {
            this.$message.error(response.message)
          }
        })
      })
    },
    resetTemp() {
      this.form.model = Object.assign({}, defaultTask)
    }
  }
}
</script>
